//
//  JZAudioPlay.m
//  JFTwxsd
//
//  Created by Peter on 2019/3/8.
//  Copyright © 2019 junfeiweiyejiaoyujituan. All rights reserved.
//

#import "JZAudioPlay.h"

static JZAudioPlay *soundplayer = nil;

@interface JZAudioPlay ()

@property (nonatomic, strong) AVSpeechSynthesisVoice *voiceConfig;
@property (nonatomic, strong) AVSpeechSynthesizer *synthConfig;

@end

@implementation JZAudioPlay

+ (JZAudioPlay *)SDSoundPlayerInit {
    if(soundplayer == nil) {
        soundplayer = [[JZAudioPlay alloc]init];
        [soundplayer setDefaultWithVolume:-1.0 rate:-1.0 pitchMultiplier:-1.0];
    }
    return soundplayer;
}

//播放声音
- (void)play:(NSString *)string {
    if(string && string.length > 0) {
        AVSpeechSynthesizer *player  = [[AVSpeechSynthesizer alloc]init];
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:string];//设置语音内容
        utterance.voice  = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//设置语言
        utterance.rate   = self.rate;  //设置语速
        utterance.volume = self.volume;  //设置音量（0.0~1.0）默认为1.0
        utterance.pitchMultiplier    = self.pitchMultiplier;  //设置语调 (0.5-2.0)
        utterance.postUtteranceDelay = 1; //目的是让语音合成器播放下一语句前有短暂的暂停
        [player speakUtterance:utterance];
    }
}

//初始化配置
/**
 *  设置播放的声音参数 如果选择默认请传入 -1.0
 *
 *  @param aVolume          音量（0.0~1.0）默认为1.0
 *  @param aRate            语速（0.0~1.0）
 *  @param aPitchMultiplier 语调 (0.5-2.0)
 */
- (void)setDefaultWithVolume:(float)aVolume rate:(CGFloat)aRate pitchMultiplier:(CGFloat)aPitchMultiplier {
    self.rate   = aRate;
    self.volume = aVolume;
    self.pitchMultiplier = aPitchMultiplier;
    if (aRate == -1.0) {
        self.rate = 1;
    }
    if (aVolume == -1.0) {
        self.volume = 1;
    }
    if (aPitchMultiplier == -1.0) {
        self.pitchMultiplier = 1;
    }
}

- (void)addOperations:(NSString *)title {
    [[self mainQueue] addOperation:[self customOperation:title]];
}

- (NSOperationQueue *)mainQueue {
    return [NSOperationQueue mainQueue];
}

- (NSOperation *)customOperation:(NSString *)content {
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        AVSpeechUtterance *utterance = nil;
        @autoreleasepool {
            utterance = [AVSpeechUtterance speechUtteranceWithString:content];
            utterance.rate = 0.5;
        }
        utterance.voice = self.voiceConfig;
        [self.synthConfig speakUtterance:utterance];
    }];
    return operation;
}

- (AVSpeechSynthesisVoice *)voiceConfig {
    if (_voiceConfig == nil) {
        _voiceConfig = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    }
    return _voiceConfig;
}

- (AVSpeechSynthesizer *)synthConfig {
    if (_synthConfig == nil) {
        _synthConfig = [[AVSpeechSynthesizer alloc] init];
    }
    return _synthConfig;
}

@end
